#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
from flask import Blueprint
from flask import request
from flask_api import status
from car_base.car_drive import CarDrive
import multiprocessing as mp
from tools.config import Config as cfg
import json

car_action_control_bp = Blueprint('car_action_control_bp', __name__)

_car:CarDrive                      # 定义_car的类型
_flask_dict:dict                    # flask框架接收到的状态标志位

def setVisualControlHandel(flask_dict, car_drive:CarDrive):
    global _car, _flask_dict
    _car = car_drive
    _flask_dict = flask_dict

def request_parse(request_data):
    ret_data = None
    if request_data.method == "POST":
        ret_data = request_data.get_json()
    elif request_data.method == "GET":
        ret_data = json.loads(request_data.data.decode("utf8"))
    return ret_data


@car_action_control_bp.route('/carControl', methods=['GET', 'POST'])
def trackControl():
    global _car
    # if not isinstance(_car, (car_drive,)):
    #     return 'error', status.HTTP_500_INTERNAL_SERVER_ERROR

    ret_msg = 'ok', status.HTTP_200_OK
    data = request_parse(request)
    command_val = data.get("commandType")

    if isinstance(command_val, type(None)):
        return "commandType Can not be empty", status.HTTP_400_BAD_REQUEST
    commandSets = ['FORWARD', 'BACK', 'TURNLEFT', 'TURNRIGHT', 'STOP']
    if not command_val.upper() in commandSets:
        return 'commandType can only be [FORWARD， BACK， TURNLEFT， TURNRIGHT, STOP]', status.HTTP_400_BAD_REQUEST

    speed_val = data.get("speed")
    code_disk_val = data.get("codeDisk")
    if (isinstance(speed_val, type(None)) and isinstance(code_disk_val, type(None))):
        return "require parameters speed, codedisk", status.HTTP_400_BAD_REQUEST

    try:
        speed_val = int(speed_val) % 100
        code_disk_val = int(code_disk_val)
    except Exception as e:
        import logging
        logging.exception(e)
        return "parameter type must be integer", status.HTTP_400_BAD_REQUEST

    # 控制逻辑
    if command_val.upper() == commandSets[0]:  # 前进
        _car.go(speed_val, code_disk_val)
    elif command_val.upper() == commandSets[1]:
        _car.back(speed_val, code_disk_val)
    elif command_val.upper() == commandSets[2]:
        _car.left(speed_val)
    elif command_val.upper() == commandSets[3]:
        _car.right(speed_val)
    elif command_val.upper() == commandSets[4]:
        _car.stop()
    return ret_msg

@car_action_control_bp.route('/carTask', methods=['GET', 'POST'])
def carTask():
    ret_msg = 'ok', status.HTTP_200_OK
    data = request_parse(request)
    print("data", data)

    command_val = data.get("commandType")
    task_flag = command_val.upper()

    # 将无人车任务启动状态存放入多进程全局共享dict中
    _flask_dict[cfg.CAR_TASK] = task_flag

    return ret_msg